package com.gxa.hualian.web.servlet;

import com.gxa.hualian.entity.Coupon;
import com.gxa.hualian.entity.User;
import com.gxa.hualian.exception.BusinessException;
import com.gxa.hualian.exception.ExceptionCode;
import com.gxa.hualian.service.CouponService;
import com.gxa.hualian.service.UserService;
import com.gxa.hualian.service.impl.CouponServiceImpl;
import com.gxa.hualian.service.impl.UserServiceImpl;
import com.gxa.hualian.util.JsonResult;
import com.gxa.hualian.util.ResponseUtil;
import com.gxa.hualian.util.StringUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 *优化: 采用JsonResult  和ResponseUtil处理响应结果
 * @author bill
 * @date 2022/4/28 15:28
 */
//@WebServlet(name = "UserServlet",urlPatterns = "/user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    private CouponService couponService=new CouponServiceImpl();
    // 构建User对象
    private User user = new User();
    // 声明JsonResult对象
    private JsonResult jsonResult = new JsonResult();
    private ResponseUtil responseUtil=null;
    private void registerHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {


        String phone = req.getParameter("phone");
        String smsCode=req.getParameter("smsCode");

        //判读用户输入的短信验证码和服务器的是否一致
        if (!StringUtil.isEmpty(smsCode)){
            HttpSession session=req.getSession();
            Object captcha = session.getAttribute("captcha");
            System.out.println("reg captcha:"+captcha);
            if (smsCode.equals(captcha)){
                user.setPhone(phone);

                // 调用service操作, 必须在Servlet中(最后的管控)处理异常
                // 这个异常的处理的合理方式: 捕获
                // 原则: 不能让前端看到这个异常信息(包含大量的服务器信息) : 500状态
                // TODO 自己捕获, 根据异常信息,给前端返回加工后的数据( 服务器开小差了)
                User register = null;




                // 此时的注册方法,含有抛出的BusiniessException
                register = userService.register(user);

                //3. 向Map中添加数据
                jsonResult.setCode("1");
                //2. 声明ResponseUtil对象,完成写操作
                responseUtil = new ResponseUtil(resp,jsonResult);
                responseUtil.write();
            }


        }




    }
    private void loginHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {

        String phone = req.getParameter("phone");
        System.out.println(phone);
        user.setPhone(phone);


        userService.login(user);
        //登陆成功
        //生成token(唯一性/复杂度)
        String token= UUID.randomUUID().toString().replaceAll("-","");
        //把服务器的token存到session中
        HttpSession session=req.getSession();
        session.setAttribute("token",token);
//        session.removeAttribute("token");
        jsonResult.set("token",token);
        //3. 向Map中添加数据
        jsonResult.setCode("1");
        jsonResult.setMsg("登录成功!");

        jsonResult.set("phone",phone);
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        //写入
        responseUtil.write();

    }
    private void selectAllHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {

        //查询业务需要前端携带token请求头


        List<User> lists= userService.sellectAll();

        jsonResult.setData(lists);
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        responseUtil.write();

    }
    private void selectByPageHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        Integer page=Integer.parseInt(req.getParameter("page"));
        Integer limit=Integer.parseInt(req.getParameter("limit"));

            //调用业务方法
            List<User> lists= userService.selectByPage(page,limit);
            List<User> users = userService.sellectAll();

            String count= String.valueOf(users.size());

            jsonResult.setCode("0");

            jsonResult.setData(lists);
            jsonResult.setCount(count);
            //2. 声明ResponseUtil对象,完成写操作
            responseUtil = new ResponseUtil(resp,jsonResult);
            responseUtil.write();

    }
    private void deleteByIdHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        //转换
        Integer id=Integer.parseInt(req.getParameter("id"));
        System.out.println(id);


        Boolean aBoolean = userService.deleteById(id);

        jsonResult.setCode("1");
        jsonResult.setMsg("删除成功");
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        responseUtil.write();




    }
    private void updateByIdHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        //转换
        Integer id=Integer.parseInt(req.getParameter("id"));

        String phone = req.getParameter("phone");

        user.setId(id);

        user.setPhone(phone);


        userService.updateById(user);

        jsonResult.setCode("1");
        jsonResult.setMsg("修改成功");
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        responseUtil.write();

    }
    private void selectLikeNameHandler(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        String value=req.getParameter("name");
        List<User> lists = userService.selectLikeName(value);
//        List<User> users = userService.sellectAll();
        String count= String.valueOf(lists.size());
        jsonResult.setCode("0");
        jsonResult.setData(lists);
        jsonResult.setCount(count);
        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        responseUtil.write();

    }
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        System.out.println("UserServlet 被访问了");
        // 创建ServletContext
        ServletContext servletContext = req.getServletContext();

        String encoding = servletContext.getInitParameter("encoding");

        // 接收前端的请求参数时,如果有中文, 也采用UTF-8编码格式来处理
        req.setCharacterEncoding(encoding);
        //获取请求路径

        String handlerType=req.getHeader("handlerType");
        System.out.println(handlerType);
        // 支持中文
        resp.setCharacterEncoding(encoding);
        resp.setContentType("application/json;charset="+encoding);
        try {
            if ("login".equals(handlerType)){
                loginHandler(req,resp);
            }else if ("register".equals(handlerType)){
                registerHandler(req,resp);
            }else if ("selectAll".equals(handlerType)){
                selectAllHandler(req,resp);
            }else if ("deleteById".equals(handlerType)){
                deleteByIdHandler(req,resp);
            }else if ("updateById".equals(handlerType)){
                updateByIdHandler(req,resp);
            }else if ("getList".equals(handlerType)){
                selectByPageHandler(req,resp);
            }else if ("getLikeList".equals(handlerType)){
                selectLikeNameHandler(req,resp);
            }else if("getCpnListForWeb".equals(handlerType)){
                getcpnListForWebHandler(req,resp);
            }
        }catch (Exception e){
            //当有异常发生,当前Servlet不做处理,统一转发给ExceptionServlet
            //利用request作用域对象,将e传递
            req.setAttribute("exception",e);
            //实现转发
            this.getServletContext().getRequestDispatcher("/error").forward(req,resp);
        }



    }

    private void getcpnListForWebHandler(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String phone = req.getParameter("phone");
        Map<String, List<Coupon>> conListForWeb = couponService.getConListForWeb(phone);
        Set<Map.Entry<String, List<Coupon>>> entries = conListForWeb.entrySet();
        jsonResult.setCode("1");
        jsonResult.setData(conListForWeb);

        //2. 声明ResponseUtil对象,完成写操作
        responseUtil = new ResponseUtil(resp,jsonResult);
        responseUtil.write();

    }
}
